package cn.fl.mcr.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ExcelReportUtil {
	
    private static final Logger logger = LoggerFactory.getLogger(ExcelReportUtil.class);
    
    /**
     * 
     * @Title: exportExcelReportPage   
     * @Description:分页导出excel 65000（65000一个sheet页）
     * @param: @param title
     * @param: @param header
     * @param: @param content
     * @param: @param response
     * @param: @param request      
     * @return: void      
     * @throws
     */
    public static void exportExcelReportPage(String title,String[][] header, List<Map<String, Object>> content,
                                HttpServletResponse response,HttpServletRequest request){

        //将excel数据分页
        List[] totals = splitList(content,65000);
        logger.info("ExcelReportUtil>>exportExcelReportPage>>excel页数:"+totals.length);
        // 创建工作簿
//        HSSFWorkbook wb = new HSSFWorkbook();
        SXSSFWorkbook wb = new SXSSFWorkbook(10000);
        if(null != totals && totals.length > 0){
            // 由工作簿创建工作表
            for (int j = 0; j < totals.length; j++) {
                Sheet sheet = wb.createSheet("sheet" + (j + 1));
                // 在工作表中创建行
                Row row = sheet.createRow(0);
                // 创建单元格,设置每个单元格的字段名
                Cell cell = null;
                for (int i = 0; i < header[0].length; i++) {
                    cell = row.createCell(i);
                    cell.setCellValue(header[0][i]);
                }
                List<Map<String, Object>> list = totals[j];

                for (int i = 0; i < list.size(); i++) {
                    row = sheet.createRow(i + 1);
                    for(int x = 0; x < header[1].length; x++){
                        cell = row.createCell(x);
                        if (list.get(i).get(header[1][x]) == null){
                            cell.setCellValue("");
                        }else{
                            cell.setCellValue(String.valueOf(list.get(i).get(header[1][x])));
                        }
                    }
                }
            }
            logger.info("ExcelReportUtil>>exportExcelReportPage>>数据组装完成");
        }else{
            Sheet sheet = wb.createSheet("sheet1");
            // 在工作表中创建行
            Row row = sheet.createRow(0);
            // 创建单元格,设置每个单元格的字段名
            Cell cell = null;
            for (int i = 0; i < header[0].length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(header[0][i]);
            }
        }

        ServletOutputStream sos = null;

        try {
            // 解决中文文件名乱码问题
            if (request.getHeader("User-Agent").toLowerCase()
                    .indexOf("firefox") > 0) {
                title = new String(title.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
            } else if (request.getHeader("User-Agent").toUpperCase()
                    .indexOf("MSIE") > 0) {
                title = URLEncoder.encode(title, "UTF-8");// IE浏览器
            }else if (request.getHeader("User-Agent").toUpperCase()
                    .indexOf("CHROME") > 0) {
                title = new String(title.getBytes("UTF-8"), "ISO8859-1");// 谷歌
            }

            String fileName = title + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msexcel");// 设置为下载application/x-download
            response.setHeader("Content-Disposition", "inline;filename=\"" + fileName + ".xlsx\"");
            response.resetBuffer();

            sos = response.getOutputStream();
            wb.write(sos);
            sos.flush();
            logger.info("ExcelReportUtil>>exportExcelReportPage>>导出数据完成");
        } catch (IOException e) {
        	logger.error("导出excel工具类报错", e);
        } finally {
            try {
                sos.close();
                wb.dispose();
            } catch (IOException e) {
            	logger.error("导出excel工具类报错", e);
            }
        }
    }
    
    /**
     * 
     * @Title: splitList   
     * @Description: sheet页码
     * @param: @param list
     * @param: @param pageSize
     * @param: @return      
     * @return: List[]      
     * @throws
     */
    public static List[] splitList(List list, Integer pageSize) {
		if (pageSize == null) {
			pageSize = 300;
		}
		int total = list.size();
		// 总页数
		int pageCount = total % pageSize == 0 ? total / pageSize : total
				/ pageSize + 1;
		List[] result = new List[pageCount];
		for (int i = 0; i < pageCount; i++) {
			int start = i * pageSize;
			// 最后一条可能超出总数
			int end = start + pageSize > total ? total : start + pageSize;
			List subList = list.subList(start, end);
			result[i] = subList;
		}
		return result;
	}
}
